import router from 'umi/router';
import { Layout, Menu } from 'antd';
import styles from '@/layouts/styles.less';
import * as Icons from '@ant-design/icons';
import { matchRoutes } from 'react-router-config';
import React, { useCallback, useEffect, useMemo, useState } from 'react';

const matchKeys = (routes: any[], path: string) => (
  matchRoutes(routes, path).map(({ match }: any) => match.path)
);

const filterItems = (items = []) => {
  return items.filter((item: any) => item.path && !item.hiddenMenu);
};

const MenuContent = (props: any) => {
  const { routes = [] } = props.route;
  const { pathname } = props.location;

  const selectedKeys = useMemo(() => (
    matchKeys(routes, pathname)
  ), [pathname]);

  const [
    openKeys,
    setOpenKeys,
  ] = useState<string[]>(selectedKeys);

  useEffect(() => {
    setOpenKeys(selectedKeys);
  }, [pathname, selectedKeys]);

  const triggerOpenKeys = useCallback(({ key }) => {
    const keys = new Set<string>(openKeys);
    if (!keys.has(key)) {
      keys.add(key);
    } else {
      keys.delete(key);
    }
    setOpenKeys([...keys]);
  }, [openKeys]);

  const renderItem = (item: any) => {
    let { routes = [] } = item;
    routes = filterItems(routes);
    const Icon:any = Icons[
      item.icon as never];
    if (routes.length) {
      return (
        <Menu.SubMenu
          key={item.path}
          title={item.title}
          icon={Icon ? <Icon /> : null}
          onTitleClick={triggerOpenKeys}
          children={routes.map(renderItem)}
        />
      );
    }
    return (
      <Menu.Item
        key={item.path}
        children={item.title}
        icon={Icon ? <Icon /> : null}
        onClick={() => router.push(item.path)}
      />
    );
  };
  return (
    <Layout.Sider
      collapsed={false}
      className={styles.left_menu}
    >
      <Menu
        theme="dark"
        mode="inline"
        openKeys={openKeys}
        selectedKeys={selectedKeys}
        className={styles.menu_content}
        children={filterItems(routes).map(renderItem)}
      />
    </Layout.Sider>
  );
};

export default MenuContent;
